/*Write a function a t o i (c o n s t c h a r *) that takes a string containing digits and returns the
corresponding i n t . For example, a t o i ("1 2 3 ") is 1 2 3 . Modify a t o i () to handle C++ octal and
hexadecimal notation in addition to plain decimal numbers. Modify a t o i () to handle the C++
142 Expressions and Statements Chapter 6
character constant notation.*/
#include <iostream>
#include <string>
using std::cout;
using std::endl;

const std::string letter = "0123456789ABCDEF";
inline int findindex(char c)
{
    for(int i = 0; i < 16; i++)
        if(letter[i] == c)
            return i;
    return 0;
}
inline int f(int a,int b)
{
    int ret = 1;
    for(int i = 0; i < b; i++)
    {
        ret *= a;
    }
    return ret;
}
    
int atoi(const char* pdigits)
{
    int unit = 0;
    int length = 0;
    
    if (pdigits == 0)
    {
        return 0;
    }
    int str_len = strlen(pdigits);
    
    if( pdigits[0] == '0')
    {
        if(str_len == 1)
        {
            return 0;
        }
        if(str_len > 2 && (pdigits[1] == 'x' || pdigits[1] == 'X'))
        {
            unit = 16;
            length = str_len - 2;
            
        }
        else
        {
            unit = 8;
            length = str_len - 1;
        }
    }
    else
    {
        unit = 10;
        length = str_len;
    }
    int result = 0;
    for(int i = 0; i < length; ++i)
    {
        char c = pdigits[str_len - 1 -i ] ;
        result += (f(unit,i)* findindex(c));
    }
    return result;
}
int main()
{
    cout << atoi("123") << endl;
    cout << atoi("0x123") << endl;
    cout << atoi("090") << endl;
}

    
